﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using ProjectManageSystemApi.Models;
using ProjectManageSystemApi.Services;
using ProjectManageSystemApi.Utilities;

namespace ProjectManageSystemApi.Controllers
{
    [Authorize]
    [Route("api/[controller]")]
    [ApiController]
    [ApiExplorerSettings(GroupName = Grouping.GroupName_v1)]
    public class ProjectItemImagesController : Controller
    {
        readonly IProjectItemImageInfoServices _itemImage;
        readonly IProjectItemInfoServices _itemInfo;
        readonly IUserServices _user;
        public ProjectItemImagesController(IProjectItemInfoServices itemInfo, IUserServices user, IProjectItemImageInfoServices itemImage) 
        {
            _itemInfo = itemInfo;
            _itemImage = itemImage;
            _user = user;
        }

        [HttpPost,Route("InsertMany")]
        public ApiResult InsertMany(AddProjectItemImageInfoDto itemImages) 
        {
            if (itemImages == null || itemImages.ItemId == 0 || itemImages.Images.Count == 0)
            {
                return ApiResultStatus.Fail(ApiResultCodes.PARAMS_FAILED);
            }

            string token = Request.GetToken();
            if (string.IsNullOrWhiteSpace(token))
            {
                return ApiResultStatus.Fail(ApiResultCodes.PARAMS_FAILED);
            }
            if (!_user.GetUserIdByToken(token, out long userId))
            {
                return ApiResultStatus.Fail(ApiResultCodes.PARAMS_FAILED);
            }

            if (!_itemInfo.HasExistItemId(itemImages.ItemId))
            {
                return ApiResultStatus.Fail(ApiResultCodes.DATA_NOT_EXIST);
            }

            return ApiResultStatus.Create(_itemImage.InsertMany(itemImages, userId), ApiResultCodes.OPERATION_FAILED);
        }

        [HttpGet, Route("GetAllImagesByItemId")]
        public ApiResult GetAllImagesByItemId([FromQuery]int itemId)
        {
            if (itemId <= 0)
            {
                return ApiResultStatus.Fail(ApiResultCodes.PARAMS_FAILED);
            }
            if (!_itemInfo.HasExistItemId(itemId))
            {
                return ApiResultStatus.Fail(ApiResultCodes.DATA_NOT_EXIST);
            }
            var result = _itemImage.GetImagesByItemId(itemId);
            return ApiResultStatus.Success(result);
        }


    }
}
